package com.sq.loginservice.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.sq.api.user.UserServiceApi;
import com.sq.api.user.model.LoginUser;
import com.sq.common.constants.Constants;
import com.sq.common.exception.server.ServiceException;
import com.sq.common.utils.StringUtils;
import com.sq.common.web.R;
import com.sq.loginservice.service.LogService;
import com.sq.loginservice.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author Li sir
 * @Date 2024/9/27
 */

@Service
public class LoginserServiceImpl implements LoginService {

    @Autowired
    private UserServiceApi userServiceApi;

    @Autowired
    private SysPasswordService sysPasswordService;

    @Autowired
    private LogService logService;

    @Override
    public LoginUser login(String userName, String password) {

        // 1. 校验参数
        if (StringUtils.isAnyBlank(userName, password))
        {
            logService.saveLog(userName,Constants.LOGIN_FAIL,"用户/密码未填写");
            throw new ServiceException("用户/密码未填写");
        }
        // 2. 获取用户信息
        R<LoginUser> userInfo = userServiceApi.getUserInfo(userName);

        if (Objects.isNull(userInfo) || !Constants.SUCCESS.equals(userInfo.getCode())){
            logService.saveLog(userName,Constants.LOGIN_FAIL,"登录用户：" + userName + " 不存在");
            throw new ServiceException("登录用户：" + userName + " 不存在");
        }

        LoginUser loginUser = userInfo.getData();

        // 3.  校验密码
        sysPasswordService.validate(loginUser.getSysUser(),password);

        logService.saveLog(userName,Constants.LOGIN_SUCCESS,userName+"登录成功");

        return loginUser;
    }

    @Override
    public void loginOut(String userName) {
        if (StringUtils.isBlank(userName)){
            StpUtil.logout();
        }else {
            StpUtil.logout(userName);
        }
    }

    @Override
    public String register(String userName, String password) {
        return null;
    }
}
